package sjtu.ist.warehouse4ws.tool.file;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import sjtu.ist.warehouse4ws.epc2bpmn.ParserEpc;
import sjtu.ist.warehouse4ws.model.Company;
import sjtu.ist.warehouse4ws.model.Domainmodel;
import sjtu.ist.warehouse4ws.model.Domainmodelattr;
import sjtu.ist.warehouse4ws.model.Domainmodelstate;
import sjtu.ist.warehouse4ws.model.Epcunit;
import sjtu.ist.warehouse4ws.model.Epcunits;
import sjtu.ist.warehouse4ws.model.Fileinfo;
import sjtu.ist.warehouse4ws.model.Functionpoint;
import sjtu.ist.warehouse4ws.model.Functions;
import sjtu.ist.warehouse4ws.model.Parameter;
import sjtu.ist.warehouse4ws.model.Permission;
import sjtu.ist.warehouse4ws.model.Permissionresources;
import sjtu.ist.warehouse4ws.model.Privilege;
import sjtu.ist.warehouse4ws.model.Process;
import sjtu.ist.warehouse4ws.model.Role;
import sjtu.ist.warehouse4ws.model.Rolepermissions;
import sjtu.ist.warehouse4ws.service.CompanyService;
import sjtu.ist.warehouse4ws.service.DomainModelAttributeService;
import sjtu.ist.warehouse4ws.service.DomainModelService;
import sjtu.ist.warehouse4ws.service.DomainModelStateService;
import sjtu.ist.warehouse4ws.service.EpcUnitService;
import sjtu.ist.warehouse4ws.service.EpcunitsService;
import sjtu.ist.warehouse4ws.service.FileInfoService;
import sjtu.ist.warehouse4ws.service.FunctionpointService;
import sjtu.ist.warehouse4ws.service.FunctionsService;
import sjtu.ist.warehouse4ws.service.OplogService;
import sjtu.ist.warehouse4ws.service.ParameterService;
import sjtu.ist.warehouse4ws.service.PermissionService;
import sjtu.ist.warehouse4ws.service.PermissionresourcesService;
import sjtu.ist.warehouse4ws.service.PrivilegeService;
import sjtu.ist.warehouse4ws.service.ProcessService;
import sjtu.ist.warehouse4ws.service.RoleService;
import sjtu.ist.warehouse4ws.service.RolepermissionsService;
import sjtu.ist.warehouse4ws.tool.MyUtils;
import sjtu.ist.warehouse4ws.tool.ParseDomainModel;
import sjtu.ist.warehouse4ws.tool.ParserFunctionpoint;
import sjtu.ist.warehouse4ws.tool.ParserPermission;
import sjtu.ist.warehouse4ws.tool.ParserProcess;
import sjtu.ist.warehouse4ws.tool.ParserRole;

import com.googlecode.jsonplugin.annotations.JSON;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileInfoAction extends ActionSupport {

	private String id;
	private String fileName;
	private String project;
	private String department;
	private String version;
	private int type;

	private FileInfoService fileInfoService;
	private EpcunitsService epcUnitsService;
	private EpcUnitService epcUnitService;

	private PermissionService permissionService;
	private PermissionresourcesService permissionresourcesService;

	private RoleService roleService;
	private RolepermissionsService rolepermissionsService;

	private DomainModelAttributeService domainModelAttributeServiceImpl;
	private DomainModelService domainModelServiceImpl;
	private DomainModelStateService domainModelStateService;

	private FunctionpointService functionpointService;
	private ParameterService parameterService;

	private FunctionsService functionsService;
	private ProcessService processService;
	private PrivilegeService privilegeService;
	private CompanyService companyService;
	private OplogService oplogService;
	
	private boolean success=false;

	public void setPrivilegeService(PrivilegeService privilegeService) {
		this.privilegeService = privilegeService;
	}

	public void setOplogService(OplogService oplogService) {
		this.oplogService = oplogService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public EpcUnitService getEpcUnitService() {
		return epcUnitService;
	}

	public void setEpcUnitService(EpcUnitService epcUnitService) {
		this.epcUnitService = epcUnitService;
	}

	public void setEpcunitsService(EpcunitsService epcUnitsService) {
		this.epcUnitsService = epcUnitsService;
	}

	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}

	public void setPermissionresourcesService(
			PermissionresourcesService permissionresourcesService) {
		this.permissionresourcesService = permissionresourcesService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public void setRolepermissionsService(
			RolepermissionsService rolepermissionsService) {
		this.rolepermissionsService = rolepermissionsService;
	}

	public String updateFileInfo() {
		ActionContext actionContext = ActionContext.getContext();
		Map session = actionContext.getSession();

		String user_id = session.get("user_id").toString();
		String user_company = session.get("user_company").toString();

		// List<Fileinfo> list=fileInfoService.findFileInfoByName(fileName);
		// Fileinfo fileInfo=list.get(0);
		Fileinfo fileInfo = fileInfoService.getFileInfo(id);

		//fileInfo.setName(fileInfo.getId());
		try {
			if(project != null){
			project = new String(project.getBytes("ISO-8859-1"), "UTF-8");}
			if(version != null){
			version = new String(version.getBytes("ISO-8859-1"), "UTF-8");}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//System.out.println("pro"+project);
		fileInfo.setProject(project);
		fileInfo.setDepartment(department);
		fileInfo.setType(type);
		fileInfo.setVersion(version);
		fileInfo.setCompany(user_company);

		String path = fileInfo.getXmlpath();
		int in = path.lastIndexOf("\\");
		String temp = path.substring(0, in + 1);
		String newDir = temp.concat(getTypeById(type));
		String newPath = newDir + path.substring(in, path.length());

		MyUtils.mkDirectory(newDir);
		MyUtils.moveFile(path, newPath);
		fileInfo.setXmlpath(newPath);
		fileInfoService.updateFileInfo(fileInfo);
		parseById(type, newPath, id);

		// 向权限列表插入数据
		// User user=userService.get(Integer.parseInt(fileInfo.getCreator()));
		List<Company> clist = companyService.getAllCompanies();
		for (Company c : clist) {
			if(c.getId().equals(user_company)){
				Privilege p = new Privilege(java.util.UUID.randomUUID().toString(),
						fileInfo.getId(), c.getId(), 1, 1, 1);
				privilegeService.save(p);
			}else{
				Privilege p = new Privilege(java.util.UUID.randomUUID().toString(),
						fileInfo.getId(), c.getId(), 0, 0, 0);
				privilegeService.save(p);
			}
		}
		
		//插入日志记录
		oplogService.recordLog(user_id, fileInfo.getId(), "上传模型文件", "uploadop");
		return SUCCESS;
	}
	
	public String deleteFileInfo(){
//		if(!privilegeService.checkPrivilege(id, "delete")){
//			success=false;
//			return SUCCESS;
//		}
		
		Fileinfo fileInfo=fileInfoService.getFileInfo(id);
		MyUtils.deleteFile(fileInfo.getXmlpath());
		fileInfoService.deleteFileInfo(id);
		success=true;
		
		//插入日志记录
		ActionContext actionContext = ActionContext.getContext();
		Map session = actionContext.getSession();
		String user_id = session.get("user_id").toString();
		oplogService.recordLog(user_id, fileInfo.getId(), "删除模型文件："+fileInfo.getName(), "deleteop");
		
		return SUCCESS;
	}

	public String getTypeById(int type) {
		switch (type) {
		case 1:
			return "process";
		case 2:
			return "function";
		case 3:
			return "department";
		case 4:
			return "domain";
		case 5:
			return "epc";
		case 6:
			return "permission";
		case 7:
			return "role";
		default:
			return "";
		}
	}

	public void parseById(int type, String path,String fileId) {
		switch (type) {
		case 1: {
			ParserProcess pp = new ParserProcess();
			Process process = pp.reserveProcess(path);
			process.setFileId(fileId);
			ArrayList<Functions> fs = pp.reserveFunctions(path);

			processService.save(process);
			for (int i = 0; i < fs.size(); i++) {
				functionsService.sava(fs.get(i));
			}

			break;
		}

		case 2: {
			ParserFunctionpoint pfp = new ParserFunctionpoint();
			Functionpoint fp = pfp.reservePoint(path);
			fp.setFileId(fileId);
			ArrayList<Parameter> param = pfp.reserveParameter(path);
			functionpointService.savaFunctionpoint(fp);
			for (int i = 0; i < param.size(); i++) {
				parameterService.save(param.get(i));
			}

			break;
		}

		case 3:

		case 4: {
			ParseDomainModel pdm = new ParseDomainModel();
			Domainmodel dmodel = pdm.reserveModel(path);
			dmodel.setFileId(fileId);
			ArrayList<Domainmodelattr> dmodelattr = pdm
					.reserveDomianmodelattr(path);
			ArrayList<Domainmodelstate> dmodelstate = pdm.reserveState(path);
			domainModelServiceImpl.saveDomainModel(dmodel);
			for (int i = 0; i < dmodelattr.size(); i++) {
				domainModelAttributeServiceImpl
						.SavetDomainModelAttribute(dmodelattr.get(i));
			}
			for (int i = 0; i < dmodelstate.size(); i++) {
				domainModelStateService
						.savaDomainmodelstate(dmodelstate.get(i));
			}
			break;
		}
		case 5: {
			try {
				// 解析后存入数据库
				List<Epcunits> epcunitsList = epcUnitsService
						.getEpcunitsListById(fileId.substring(0,
								fileId.length() - 4));
				if (epcunitsList.toString() == "[]") {
					Epcunits epcunits = ParserEpc.parse(path);
					epcunits.setFileId(fileId);
					epcunits.setName(epcunits.getEpcUnits().get(0).getName());

					epcunits.setId(fileId.substring(0,fileId.length() - 4));
					epcUnitsService.saveEpcUnits(epcunits);
					int in = path.lastIndexOf("\\");
					String epcId = fileId.substring(0,fileId.length() - 4);

					List<Epcunit> list = epcunits.getEpcUnits();
					for (Epcunit epcunit : list) {
						epcunit.setEpcId(epcId);
						String eid = String.valueOf(epcunit.getId());
						String s = "";

						List<Integer> next = epcunit.getNext();

						for (int i : next) {
							s = s + i + ",";
						}
						epcunit.setNextstring(s);
						epcunit.setModelId(epcId + "_" + eid);
					}
					epcUnitService.addEpcUnit(list);
				}
			}
			catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
		case 6: {
			try {
				List<Permission> permissionList = permissionService
						.getPermissionListById(fileName.substring(0,
								fileName.length() - 4));
				if (permissionList.toString() == "[]") {
					ParserPermission parserPermission = new ParserPermission();
					Permission permission = parserPermission.parse(path);

					permissionService.addPermission(permission);
					List<Permissionresources> prs = parserPermission
							.parsePR(path);

					for (Permissionresources pr : prs) {
						permissionresourcesService.addPermissionresources(pr);
					}
				}
				break;
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
		case 7: {
			try {
				List<Role> roleList = roleService.getRoleListById(fileName
						.substring(0, fileName.length() - 4));
				if (roleList.toString() == "[]") {
					ParserRole parserRole = new ParserRole();
					Role role = parserRole.parse(path);
					role.setFileId(fileId);
					roleService.addRole(role);

					List<Rolepermissions> rps = parserRole.parseRP(path);

					for (Rolepermissions rp : rps) {
						rolepermissionsService.addRolepermissions(rp);
					}
				}
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
		default:
		}
	}

	public void setFileInfoService(FileInfoService fileInfoService) {
		this.fileInfoService = fileInfoService;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getProject() {
		return project;
	}

	public void setProject(String project) {
		this.project = project;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	@JSON(name="success")
	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public EpcunitsService getEpcUnitsService() {
		return epcUnitsService;
	}

	public void setEpcUnitsService(EpcunitsService epcUnitsService) {
		this.epcUnitsService = epcUnitsService;
	}

	public FileInfoService getFileInfoService() {
		return fileInfoService;
	}

	public void setDomainModelAttributeService(
			DomainModelAttributeService domainModelAttributeServiceImpl) {
		this.domainModelAttributeServiceImpl = domainModelAttributeServiceImpl;
	}

	public void setDomainModelService(DomainModelService domainModelServiceImpl) {
		this.domainModelServiceImpl = domainModelServiceImpl;
	}

	public void setDomainModelStateService(
			DomainModelStateService domainModelStateService) {
		this.domainModelStateService = domainModelStateService;
	}

	public void setFunctionpointService(
			FunctionpointService functionpointService) {
		this.functionpointService = functionpointService;
	}

	public void setParameterService(ParameterService parameterService) {
		this.parameterService = parameterService;
	}

	public void setFunctionsService(FunctionsService functionsService) {
		this.functionsService = functionsService;
	}

	public void setProcessService(ProcessService processService) {
		this.processService = processService;
	}

}
